import axios from "axios";
import {stringify} from 'qs'

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 3000,
})

function request(url, method = 'GET', data = {},) {
    const options = {
        method, // HTTP请求方法，默认为GET
        headers: {'Content-Type': 'application/json'},
    }
    if (method.toUpperCase() === 'GET') {
        // 如果是get请求，将参数拼接在url上
        options.url = `${url}?${stringify(data)}`
    } else {
        options.data = JSON.stringify(data)
    }
    // 根据配置项请求相关接口
    const result = axiosInstance.request(options).then((response) => {
        return response
    }).catch(error => {
        const {  data } = error.response || error;
        // TODO: 统一报错
        return Promise.reject(data || {})
    })
    return result
}

export const get = (url, data) => request(url, 'GET', data)
export const post = (url, data) => request(url, 'POST', data)


export default request